package com.fcltuteng.db.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

import com.fcltuteng.db.MyDBHelper;
import com.fcltuteng.model.ContactModel;

public class ContactDao {
	
	private MyDBHelper dbHelper;
	
	public ContactDao(Context context, String name, CursorFactory factory, int version){
		dbHelper = new MyDBHelper(context, name, null, version);
	}
	
	public void add(String name, String company, String phone, String email, String qq, String remark){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL("insert into contacts(name, company, phone, email, qq, remark) values(?, ?, ?, ?, ?, ?)", 
				new Object[]{name, company, phone, email, qq, remark});
		db.close();
	}
	
	public void delete(String name){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL("delete from contacts where name=?", new Object[]{name});
		db.close();
	}
	
	public void update(String name, String phone){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL("update contacts set phone=? where name=?", new Object[]{phone, name});
		db.close();
	}
	
	public List<ContactModel> findAll()	{
		List<ContactModel> contactList = new ArrayList<ContactModel>();
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		
		Cursor cursor = db.rawQuery("select name,company,phone,email,qq,birthday,remark from contacts", null);
		while (cursor.moveToNext()) {
			String name = cursor.getString(cursor.getColumnIndex("name"));
			String company = cursor.getString(cursor.getColumnIndex("company"));
			String phone = cursor.getString(cursor.getColumnIndex("phone"));
			String email = cursor.getString(cursor.getColumnIndex("email"));
			String qq = cursor.getString(cursor.getColumnIndex("qq"));
			//String birthday = cursor.getString(cursor.getColumnIndex("birthday"));
			String remark = cursor.getString(cursor.getColumnIndex("remark"));
			ContactModel contactModel = new ContactModel(name, company, phone, email, qq, null, remark);
			contactList.add(contactModel);
		}
		
		db.close();		
		return contactList;
	}
}
